package org.tio.http.server.showcase.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.http.common.UploadFile;
import org.tio.http.server.annotation.RequestPath;
import org.tio.http.server.showcase.model.User;
import org.tio.http.server.util.Resps;
import org.tio.utils.hutool.FileUtil;
import org.tio.utils.json.Json;
import org.tio.utils.resp.Resp;


/**
 * ab -k -n1000000 -c10 http://127.0.0.1:8080/json
 * ab -k -n1000000 -c10 http://127.0.0.1:8080/plaintext
 *
 * @author tanyaowu
 * 2017年6月29日 下午7:53:59
 */
//@TioDoc(doc = "showcase示范工程", select = { "1", "2" })
@RequestPath(value = "/showcase")
public class ShowcaseController {

    private Logger log = LoggerFactory.getLogger(ShowcaseController.class);

    /**
     * string数组<br>
     * <input type="text" name="names" value="kobe">
     * <input type="text" name="names" value="tan">
     *
     * <br><br>Integer数组<br>
     * <input type="text" name="ids" value="11">
     * <input type="text" name="ids" value="22">
     *
     * <br><br>int数组<br>
     * <input type="text" name="primitiveIds" value="55">
     * <input type="text" name="primitiveIds" value="66">
     *
     * @param names
     * @param ids
     * @param primitiveIds
     * @param request
     * @return
     * @throws Exception
     * @author tanyaowu
     */
    @RequestPath(value = "/array")
    public Object array(String[] names, Integer[] ids, int[] primitiveIds, HttpRequest request) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("names", names);
        map.put("primitiveIds", primitiveIds);
        map.put("ids", ids);

        return map;
    }

    @RequestPath(value = "/get")
    public HttpResponse get(String before, String end, HttpRequest request) throws Exception {
        HttpResponse ret = Resps.html(request, "before:" + before + "<br>end:" + end);
        return ret;
    }

    /**
     * ab -n 100000 -k -c 100 http://127.0.0.1:8821/showcase/abtest
     * ab -n 100000 -k -c 100 http://127.0.0.1:7070/mytmq/tio/clu/empty.tmq_x
     * - -n：发出请求的总数
     * - -c：并发数
     * - -t：测试的最大时间
     * - -k：启用HTTP KeepAlive功能
     * - -p：POST请求发送的文件
     * - -T：POST请求的Content-Type -
     * - -H：自定义请求头 -
     * - -v`：详细输出 例如：
     *
     * @param before
     * @param end
     * @param request
     * @return
     * @throws Exception
     * @author talent.tan
     */
    //TioDoc(skip = true)
    @RequestPath(value = "/abtest")
    public HttpResponse abtest1(HttpRequest request) throws Exception {
        HttpResponse ret = Resps.html(request, "ok");
        return ret;
    }

    /**
     * @param args
     * @author tanyaowu
     */
    public static void main(String[] args) throws NoSuchFieldException, SecurityException {
        String x = "ppp\r\nttt";
        System.out.println(x);
        x = x.replaceAll("\r", "\\\r").replaceAll("\n", "\\\n").replaceAll("\"", "\\\"");
        System.out.println(x);

    }

    String html = "<div style='position:relation;border-radius:10px;text-align:center;padding:10px;font-size:40pt;font-weight:bold;background-color:##e4eaf4;color:#2d8cf0;border:0px solid #2d8cf0; width:600px;height:400px;margin:auto;box-shadow: 1px 1px 50px #000;position: fixed;top:0;left:0;right:0;bottom:0;'>"
            + "<a style='text-decoration:none' href='https://gitee.com/tywo45/t-io' target='_blank'>" + "<div style='text-shadow: 8px 8px 8px #99e;'>hello tio httpserver</div>"
            + "</a>" + "</div>";

    String txt = html;

    /**
     * @author tanyaowu
     */
    public ShowcaseController() {
    }

    //@TioDoc(skip = true)
    @RequestPath(value = "/404")
    public HttpResponse page404(HttpRequest request) throws Exception {
        HttpResponse ret = Resps.html(request, "自定义的404");
        return ret;
    }

    //@TioDoc(skip = true)
    @RequestPath(value = "/500")
    public HttpResponse page500(HttpRequest request) throws Exception {
        HttpResponse ret = Resps.html(request, "自定义的500");
        return ret;
    }

    @RequestPath(value = "/bean")
    public HttpResponse bean(User user, HttpRequest request) throws Exception {
        log.info(JSON.toJSONString(user));
        HttpResponse ret = Resps.json(request, Json.toFormatedJson(user));
        return ret;
    }

//	@RequestPath(value = "/httpCall")
//	public Object httpCall(User user, HttpRequest request) throws Exception {
//		okhttp3.Response response = HttpUtils.get("https://44213.tiocloud.com:8989/tio/oss/96/23/859/408/784/866/230/4140eec1913e45229888de19e42b6fcc.jpg");
//		ResponseBody responseBody = response.body();
//		String str = responseBody.string();
//		return str;
//	}

    //	@TioDoc(// doc = "bean2演示")
    @RequestPath(value = "/bean2")
    public HttpResponse bean2(User user, Integer id, HttpRequest request) throws Exception {
        HttpResponse ret = Resps.json(request, Json.toFormatedJson(user));
        return ret;
    }

    @RequestPath(value = "/date")
    public HttpResponse date(Date[] date, java.sql.Date[] sqlDate, java.sql.Timestamp[] timestamp, HttpRequest request) throws Exception {
        HttpResponse ret = Resps.json(request, Json.toFormatedJson(date) + Json.toFormatedJson(sqlDate) + Json.toFormatedJson(timestamp));
        return ret;
    }

    //@TioDoc(skip = true)
    @RequestPath(value = "/filetest")
    public HttpResponse filetest(HttpRequest request) throws Exception {
        HttpResponse ret = Resps.file(request, new File("d:/tio.exe"));
        return ret;
    }

    //@TioDoc(doc = "路径变量")
    @RequestPath(value = "/var/{name}/{id}")
    public HttpResponse var(String name, String id, String pwd, HttpRequest request) throws Exception {
        HttpResponse ret = Resps.json(request, "name:" + name + "\r\n" + "id:" + id);
        return ret;
    }

    //@TioDoc(skip = true)
    @RequestPath(value = "/test.zip")
    public HttpResponse test_zip(HttpRequest request) throws Exception {
        String root = request.httpConfig.getPageRoot(request);
        HttpResponse ret = Resps.file(request, new File(root, "test/test.zip"));
        return ret;
    }

    //@TioDoc(skip = true)
    @RequestPath(value = "/html")
    public HttpResponse html(HttpRequest request) throws Exception {
        HttpResponse ret = Resps.html(request, html);
        return ret;
    }

    //@TioDoc(skip = true)
    @RequestPath(value = "/json")
    public HttpResponse json(HttpRequest request, User user, Long longid, Byte byteid, Short shortid, Integer id, String loginname, Double doubleid) throws Exception {
        HttpResponse ret = Resps.json(request, Resp.ok().msg(Json.toFormatedJson(user)));
        return ret;
    }

    //@TioDoc(skip = true)
    @RequestPath(value = "/plain")
    public HttpResponse plain(String before, String end, HttpRequest request) throws Exception {
        String bodyString = request.getBodyString();
        HttpResponse ret = Resps.html(request, bodyString);
        return ret;
    }

    //@TioDoc(skip = true)
    @RequestPath(value = "/post")
    public HttpResponse post(String before, String end, User user, Short shortid, HttpRequest request) throws Exception {
        HttpResponse ret = Resps.html(request, "before:" + before + "<br>end:" + end + "<br>user:<pre>" + Json.toFormatedJson(user) + "</pre>");
        return ret;
    }

    //@TioDoc(skip = true)
    @RequestPath(value = "/putsession")
    public HttpResponse putsession(String value, HttpRequest request) throws Exception {
        request.getHttpSession().setAttribute("test", value, request.httpConfig);
        HttpResponse ret = Resps.json(request, "设置成功:" + value);
        return ret;
    }

    //@TioDoc(doc = "获取cookie")
    @RequestPath(value = "/getCookies")
    public Object getCookies(HttpRequest request) throws Exception {
        return request.getCookies();
    }

    //@TioDoc(skip = true)
    @RequestPath(value = "/txt")
    public HttpResponse txt(HttpRequest request) throws Exception {
        HttpResponse ret = Resps.txt(request, txt);
        return ret;
    }

    /**
     * 上传文件测试
     *
     * @param uploadFile
     * @param request
     * @param config
     * @param channelContext
     * @return
     * @throws Exception
     * @author tanyaowu
     */
//	@TioDoc(doc = "上传文件", params = { //请求字段说明
//	        @ParamDoc(name = "before", doc = "日期", required = false), //
//	} //)
//	)
    @RequestPath(value = "/upload")
    public HttpResponse upload(UploadFile uploadFile, String before, String end, HttpRequest request) throws Exception {
        HttpResponse ret;
        if (uploadFile != null) {
            String tmpDir = System.getProperty("java.io.tmpdir");
            log.info("tmpDir:" + tmpDir);
            //File file = new File("d:/" + uploadFile.getName());
            File file = new File(tmpDir + File.separator + uploadFile.getName());
            FileUtil.writeBytes(uploadFile.getData(), file);//.writeByteArrayToFile(file, uploadFile.getData());
            log.info("file uploaded successfully. {}", file.getAbsolutePath());
            ret = Resps.html(request, "文件【" + uploadFile.getName() + "】【" + uploadFile.getSize() + "字节】上传成功");
        } else {
            ret = Resps.html(request, "请选择文件再上传");
        }
        return ret;
    }
}
